@tool
extends Node2D

# 卡片工厂 - 负责卡片的生成、切换和显示逻辑

# GameConstants 通过 class_name 自动可用

signal card_changed(previous_index: int, current_index: int)
signal card_ready

var cards: Array[Node2D] = []
var previous_card_index: int = -1
var current_card_index: int = -1
var rng: RandomNumberGenerator

func _ready():
	rng = RandomNumberGenerator.new()
	rng.randomize()
	initialize_cards()
	emit_signal("card_ready")

func initialize_cards():
	"""初始化所有卡片，默认隐藏"""
	cards.clear()
	for i in range(get_child_count()):
		var card = get_child(i)
		cards.append(card)
		card.visible = false

func init_card_box():
	"""初始化卡片盒子，显示第一张卡片"""
	if cards.is_empty():
		return
	
	previous_card_index = rng.randi_range(0, GameConstants.CARD_COUNT - 1)
	current_card_index = previous_card_index
	show_card(previous_card_index)

func change_card():
	"""切换到下一张卡片"""
	if cards.is_empty():
		return
	
	previous_card_index = current_card_index
	current_card_index = get_random_card_index()
	
	hide_card(previous_card_index)
	show_card(current_card_index)
	
	emit_signal("card_changed", previous_card_index, current_card_index)

func get_random_card_index() -> int:
	"""获取随机卡片索引，避免连续相同"""
	var new_index = rng.randi_range(0, GameConstants.CARD_COUNT - 1)
	# 避免连续两张卡片相同（可以调整概率）
	if new_index == current_card_index and GameConstants.CARD_COUNT > 1:
		new_index = (new_index + 1) % GameConstants.CARD_COUNT
	return new_index

func show_card(index: int):
	"""显示指定索引的卡片"""
	if index >= 0 and index < cards.size():
		cards[index].visible = true

func hide_card(index: int):
	"""隐藏指定索引的卡片"""
	if index >= 0 and index < cards.size():
		cards[index].visible = false

func get_current_card_index() -> int:
	"""获取当前卡片索引"""
	return current_card_index

func get_previous_card_index() -> int:
	"""获取上一张卡片索引"""
	return previous_card_index

func are_cards_same() -> bool:
	"""判断当前两张卡片是否相同"""
	return previous_card_index == current_card_index

func reset():
	"""重置卡片状态"""
	previous_card_index = -1
	current_card_index = -1
	for card in cards:
		card.visible = false
